#include "Config.h"
#include <fstream>
#include <iostream>
#include <nlohmann/json.hpp>

using json = nlohmann::json;

bool loadConfig(const std::string &path, Config &cfg) {
    std::ifstream f(path);
    if (!f.is_open()) {
        std::cerr << "[Config] cannot open " << path << std::endl;
        return false;
    }
    json j;
    try {
        f >> j;
    } catch (...) {
        std::cerr << "[Config] parse error\n";
        return false;
    }
    cfg.can_device = j.value("can_device", "can0");
    cfg.can_bitrate = j.value("can_bitrate", 500000);
    cfg.web_port = j.value("web_port", 8080);
    cfg.motor_left_id = j.value("motor_left_id", 0x001);
    cfg.motor_right_id = j.value("motor_right_id", 0x002);
    cfg.heartbeat_id = j.value("heartbeat_id", 0x001);
    cfg.heartbeat_interval_ms = j.value("heartbeat_interval_ms", 100);
    cfg.control_interval_ms = j.value("control_interval_ms", 20);
    cfg.accel_per_sec = j.value("accel_per_sec", 2000);
    cfg.max_speed = j.value("max_speed", 1000);
    cfg.default_speed = j.value("default_speed", 500);
    cfg.min_speed = j.value("min_speed", 0);
    cfg.keyboard_repeat_timeout_ms = j.value("keyboard_repeat_timeout_ms", 200);


    cfg.camera_width = j.value("camera_width", 640);
    cfg.camera_height = j.value("camera_height", 480);
    cfg.camera_fps = j.value("camera_fps", 30);
    cfg.camera_device = j.value("camera_device", "/dev/video0");
    
    return true;
}
